// 科技管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Technology, ResearchProject, TechTree, ResearchFacility } from '@/types'
import { useResourcesStore } from './resources'

export const useTechnologyStore = defineStore('technology', () => {
  const resourcesStore = useResourcesStore()

  // 状态
  const technologies = ref<Record<string, Technology>>({})
  const researchProjects = ref<Record<string, ResearchProject>>({})
  const researchFacilities = ref<Record<string, ResearchFacility>>({})
  const techTree = ref<TechTree>({
    branches: ['basic', 'energy', 'industrial', 'military', 'exploration', 'biological', 'advanced'],
    technologies: [],
    connections: []
  })

  // 计算属性
  const researchedTechnologies = computed(() => {
    return Object.values(technologies.value).filter(tech => tech.isResearched)
  })

  const availableTechnologies = computed(() => {
    return Object.values(technologies.value).filter(tech => {
      if (tech.isResearched) return false
      
      // 检查前置科技是否已研究
      return tech.prerequisites.every(prereqId => {
        const prereq = technologies.value[prereqId]
        return prereq && prereq.isResearched
      })
    })
  })

  const technologiesByBranch = computed(() => {
    const byBranch: Record<string, Technology[]> = {}
    
    techTree.value.branches.forEach(branch => {
      byBranch[branch] = Object.values(technologies.value).filter(tech => tech.branch === branch)
    })
    
    return byBranch
  })

  const researchProgress = computed(() => {
    const total = Object.keys(technologies.value).length
    const researched = researchedTechnologies.value.length
    return total > 0 ? (researched / total) * 100 : 0
  })

  const totalResearchCapacity = computed(() => {
    return Object.values(researchFacilities.value).reduce((total, facility) => {
      return total + facility.capacity * facility.efficiency
    }, 0)
  })

  const activeResearchProjects = computed(() => {
    return Object.values(researchProjects.value).filter(project => project.progress < 1)
  })

  // 动作
  function initializeTechnologies() {
    // 基础科技
    technologies.value['basic_engineering'] = {
      id: 'basic_engineering',
      name: '基础工程学',
      description: '掌握基本的工程建设技术',
      branch: 'basic',
      tier: 1,
      researchCost: [
        { resourceId: 'energy', amount: 100 }
      ],
      researchTime: 300, // 5分钟
      prerequisites: [],
      effects: [
        {
          id: 'building_efficiency',
          type: 'building_efficiency',
          target: 'infrastructure',
          value: 0.1,
          modifier: 'multiply',
          technologyId: 'basic_engineering',
          description: '基础设施效率+10%'
        }
      ],
      unlocks: ['materials_science', 'power_plant'],
      icon: 'icon-engineering',
      isResearched: false,
      researchProgress: 0
    }

    technologies.value['materials_science'] = {
      id: 'materials_science',
      name: '材料科学',
      description: '研究新型材料的特性和应用',
      branch: 'basic',
      tier: 1,
      researchCost: [
        { resourceId: 'energy', amount: 150 },
        { resourceId: 'metal', amount: 100 }
      ],
      researchTime: 450,
      prerequisites: ['basic_engineering'],
      effects: [
        {
          id: 'building_cost_reduction',
          type: 'building_cost',
          target: 'all',
          value: -0.05,
          modifier: 'multiply',
          technologyId: 'materials_science',
          description: '建筑成本-5%'
        }
      ],
      unlocks: ['advanced_alloys', 'composite_materials'],
      icon: 'icon-materials',
      isResearched: false,
      researchProgress: 0
    }

    // 能源科技
    technologies.value['solar_power'] = {
      id: 'solar_power',
      name: '太阳能技术',
      description: '利用恒星能量发电',
      branch: 'energy',
      tier: 1,
      researchCost: [
        { resourceId: 'energy', amount: 200 },
        { resourceId: 'crystal', amount: 50 }
      ],
      researchTime: 600,
      prerequisites: ['basic_engineering'],
      effects: [
        {
          id: 'energy_production',
          type: 'resource_production',
          target: 'energy',
          value: 0.15,
          modifier: 'multiply',
          technologyId: 'solar_power',
          description: '能量产出+15%'
        }
      ],
      unlocks: ['nuclear_fission', 'improved_solar'],
      icon: 'icon-solar',
      isResearched: false,
      researchProgress: 0
    }

    // 工业科技
    technologies.value['automation'] = {
      id: 'automation',
      name: '自动化技术',
      description: '实现生产过程的自动化',
      branch: 'industrial',
      tier: 2,
      researchCost: [
        { resourceId: 'energy', amount: 300 },
        { resourceId: 'electronics', amount: 100 }
      ],
      researchTime: 900,
      prerequisites: ['materials_science', 'computer_science'],
      effects: [
        {
          id: 'industrial_efficiency',
          type: 'building_efficiency',
          target: 'industrial',
          value: 0.2,
          modifier: 'multiply',
          technologyId: 'automation',
          description: '工业建筑效率+20%'
        }
      ],
      unlocks: ['robotics', 'advanced_manufacturing'],
      icon: 'icon-automation',
      isResearched: false,
      researchProgress: 0
    }

    // 军事科技
    technologies.value['kinetic_weapons'] = {
      id: 'kinetic_weapons',
      name: '动能武器',
      description: '基础的动能投射武器系统',
      branch: 'military',
      tier: 1,
      researchCost: [
        { resourceId: 'energy', amount: 250 },
        { resourceId: 'metal', amount: 200 }
      ],
      researchTime: 750,
      prerequisites: ['basic_engineering'],
      effects: [
        {
          id: 'weapon_damage',
          type: 'weapon_damage',
          target: 'kinetic',
          value: 0.1,
          modifier: 'multiply',
          technologyId: 'kinetic_weapons',
          description: '动能武器伤害+10%'
        }
      ],
      unlocks: ['improved_kinetics', 'energy_weapons'],
      icon: 'icon-kinetic',
      isResearched: false,
      researchProgress: 0
    }

    // 更新科技树
    updateTechTree()
  }

  function startResearch(technologyId: string): boolean {
    const technology = technologies.value[technologyId]
    if (!technology || technology.isResearched) return false

    // 检查前置条件
    if (!technology.prerequisites.every(prereqId => {
      const prereq = technologies.value[prereqId]
      return prereq && prereq.isResearched
    })) return false

    // 检查是否已在研究
    if (researchProjects.value[technologyId]) return false

    // 检查研究成本
    if (!resourcesStore.canAfford(technology.researchCost)) return false

    // 扣除研究成本
    if (!resourcesStore.payCosts(technology.researchCost)) return false

    // 创建研究项目
    const project: ResearchProject = {
      technologyId,
      startTime: Date.now(),
      totalTime: technology.researchTime * 1000, // 转换为毫秒
      progress: 0,
      researchersAssigned: calculateResearchers(technology),
      efficiency: calculateResearchEfficiency(technology)
    }

    researchProjects.value[technologyId] = project
    return true
  }

  function cancelResearch(technologyId: string): boolean {
    const project = researchProjects.value[technologyId]
    if (!project) return false

    const technology = technologies.value[technologyId]
    if (!technology) return false

    // 返还部分研究成本
    const refundRate = Math.max(0.5, 1 - project.progress) // 至少返还50%
    technology.researchCost.forEach(cost => {
      const refundAmount = Math.floor(cost.amount * refundRate)
      resourcesStore.addResource(cost.resourceId, refundAmount)
    })

    // 删除研究项目
    delete researchProjects.value[technologyId]
    
    // 重置研究进度
    technology.researchProgress = 0

    return true
  }

  function updateResearch(deltaTime: number) {
    Object.entries(researchProjects.value).forEach(([technologyId, project]) => {
      const technology = technologies.value[technologyId]
      if (!technology) return

      // 计算研究进度
      const progressDelta = (deltaTime * project.efficiency) / project.totalTime
      project.progress = Math.min(project.progress + progressDelta, 1)
      technology.researchProgress = project.progress

      // 检查是否完成
      if (project.progress >= 1) {
        completeResearch(technologyId)
      }
    })
  }

  function completeResearch(technologyId: string) {
    const technology = technologies.value[technologyId]
    const project = researchProjects.value[technologyId]
    
    if (!technology || !project) return

    // 标记为已研究
    technology.isResearched = true
    technology.researchProgress = 1

    // 应用科技效果
    applyTechnologyEffects(technology)

    // 解锁新科技和建筑
    unlockNewContent(technology)

    // 删除研究项目
    delete researchProjects.value[technologyId]

    // 更新科技树
    updateTechTree()
  }

  function applyTechnologyEffects(technology: Technology) {
    // 应用科技效果到相应的系统
    technology.effects.forEach(effect => {
      console.log(`应用科技效果: ${effect.description}`)
      
      // 根据效果类型应用到相应的系统
      switch (effect.type) {
        case 'resource_production':
          // 影响资源生产效率
          applyResourceProductionEffect(effect)
          break
        case 'building_efficiency':
          // 影响建筑效率
          applyBuildingEfficiencyEffect(effect)
          break
        case 'population_growth':
          // 影响人口增长
          applyPopulationGrowthEffect(effect)
          break
        case 'research_speed':
          // 影响研究速度
          applyResearchSpeedEffect(effect)
          break
        default:
          console.log(`未知效果类型: ${effect.type}`)
      }
    })
  }

  function applyResourceProductionEffect(effect: any) {
    // 获取资源系统并应用生产效率加成
    const resourcesStore = useResourcesStore()
    
    if (effect.target && effect.value) {
      // 为特定资源的生产添加加成
      const productionId = `tech_${effect.technologyId}_${effect.target}`
      
      if (effect.modifier === 'multiply') {
        // 乘法加成 - 增加现有生产的百分比
        const currentProduction = resourcesStore.getResourceProduction(effect.target)
        const bonusAmount = currentProduction * effect.value
        
        resourcesStore.addProduction(productionId, {
          resourceId: effect.target,
          rate: bonusAmount,
          efficiency: 1.0,
          isActive: true
        })
      } else if (effect.modifier === 'add') {
        // 加法加成 - 直接增加生产量
        resourcesStore.addProduction(productionId, {
          resourceId: effect.target,
          rate: effect.value,
          efficiency: 1.0,
          isActive: true
        })
      }
    }
  }

  function applyBuildingEfficiencyEffect(effect: any) {
    // 应用建筑效率效果
    console.log(`应用建筑效率效果: ${effect.description}`)
    // 这里可以与建筑系统集成
  }

  function applyPopulationGrowthEffect(effect: any) {
    // 应用人口增长效果
    const resourcesStore = useResourcesStore()
    
    if (effect.target === 'population' && effect.value) {
      const productionId = `tech_${effect.technologyId}_population_growth`
      
      if (effect.modifier === 'multiply') {
        // 增加人口增长率的百分比
        const currentGrowth = resourcesStore.getResourceProduction('population')
        const bonusGrowth = currentGrowth * effect.value
        
        resourcesStore.addProduction(productionId, {
          resourceId: 'population',
          rate: bonusGrowth,
          efficiency: 1.0,
          isActive: true
        })
      }
    }
  }

  function applyResearchSpeedEffect(effect: any) {
    // 应用研究速度效果
    console.log(`应用研究速度效果: ${effect.description}`)
    // 这里可以影响研究效率计算
  }

  function unlockNewContent(technology: Technology) {
    // 解锁新的科技、建筑、舰船等
    technology.unlocks.forEach(unlockId => {
      console.log(`解锁新内容: ${unlockId}`)
    })
  }

  function calculateResearchers(technology: Technology): number {
    // 计算分配给该研究的研究人员数量
    const totalCapacity = totalResearchCapacity.value
    const activeProjects = activeResearchProjects.value.length
    
    return Math.floor(totalCapacity / Math.max(activeProjects, 1))
  }

  function calculateResearchEfficiency(technology: Technology): number {
    let efficiency = 1.0

    // 根据研究设施的专业化程度调整效率
    Object.values(researchFacilities.value).forEach(facility => {
      if (facility.specialization.includes(technology.branch)) {
        efficiency *= 1.2 // 专业化设施提供20%效率加成
      }
    })

    return efficiency
  }

  function updateTechTree() {
    techTree.value.technologies = Object.values(technologies.value)
    
    // 更新科技连接关系
    techTree.value.connections = []
    Object.values(technologies.value).forEach(tech => {
      tech.prerequisites.forEach(prereqId => {
        techTree.value.connections.push({
          from: prereqId,
          to: tech.id,
          type: 'prerequisite'
        })
      })
      
      tech.unlocks.forEach(unlockId => {
        techTree.value.connections.push({
          from: tech.id,
          to: unlockId,
          type: 'unlocks'
        })
      })
    })
  }

  function addResearchFacility(facility: ResearchFacility) {
    researchFacilities.value[facility.id] = facility
  }

  function removeResearchFacility(facilityId: string) {
    delete researchFacilities.value[facilityId]
  }

  function getTechnology(technologyId: string): Technology | undefined {
    return technologies.value[technologyId]
  }

  function getResearchProject(technologyId: string): ResearchProject | undefined {
    return researchProjects.value[technologyId]
  }

  function canResearch(technologyId: string): boolean {
    const technology = technologies.value[technologyId]
    if (!technology || technology.isResearched) return false

    // 检查前置科技
    const hasPrerequisites = technology.prerequisites.every(prereqId => {
      const prereq = technologies.value[prereqId]
      return prereq && prereq.isResearched
    })

    // 检查资源
    const hasResources = resourcesStore.canAfford(technology.researchCost)

    // 检查是否已在研究
    const notInProgress = !researchProjects.value[technologyId]

    return hasPrerequisites && hasResources && notInProgress
  }

  return {
    // 状态
    technologies,
    researchProjects,
    researchFacilities,
    techTree,
    
    // 计算属性
    researchedTechnologies,
    availableTechnologies,
    technologiesByBranch,
    researchProgress,
    totalResearchCapacity,
    activeResearchProjects,
    
    // 动作
    initializeTechnologies,
    startResearch,
    cancelResearch,
    updateResearch,
    addResearchFacility,
    removeResearchFacility,
    getTechnology,
    getResearchProject,
    canResearch
  }
})